﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Imdb;
using System.Xml.Serialization;

namespace MoviesManager
{
    public enum moviesStatuses
    {
        None,
        ImdbSynched,
        ImdbNotSynched
    }

    public enum choosedFrom
    {
        Unknown,
        PopularTitles,
        ExactMatches,
        PartialMatches
    }

    [Serializable]
    [XmlInclude(typeof(Movie))]
    [XmlInclude(typeof(MoviesResultset))]
    [XmlInclude(typeof(choosedFrom))]
    [XmlInclude(typeof(moviesStatuses))]  
    public class VMovie
    {
        public delegate void ImdbSynchronisation(string MovieName);
        public event ImdbSynchronisation ImdbSynchronisationDone;
        Imdb.Services Imdb = new Services();

        [System.Xml.Serialization.XmlIgnore]
        public List<FileInfo> MovieFiles { get; set; }

        public int ID { get; set; }
        public string OriginalName { get; set; }
        public string CurrentName { get; set; }
        public string NewName { get; set; }
        public string MovieSynhName { get; set; }

        public moviesStatuses MovieStatus { get; set; }
        public choosedFrom MovieChoosedFrom { get; set; }

        public string FullPath { get; set; }
        public int YearByName { get; set; }

        [XmlElement(IsNullable = true, ElementName = "MoviesResultSet")]
        public MoviesResultset MoviesIMDBResultset { get; set; }

        [XmlElement(IsNullable = true, ElementName = "MovieInfo")]
        public Movie MovieIMDBInfo { get; set; }

        public VMovie() 
        {
            Imdb.MovieParsed += new Imdb.Services.MovieParsedEventHandler(Imdb_MovieParsed);
            MovieChoosedFrom = choosedFrom.Unknown;
            MovieStatus = moviesStatuses.None;
            MovieFiles = new List<FileInfo>();
        }

        public void TryToChooceMovie()
        {
            if (MoviesIMDBResultset != null)
            {
                Movie tmp = null;
                List<Movie> tmpList;
                bool movieCoised = false;

                //Redirected Case
                if (MoviesIMDBResultset.ExactMatches != null && MoviesIMDBResultset.ExactMatches.Count == 1 && MoviesIMDBResultset.PopularTitles == null && MoviesIMDBResultset.PopularTitles == null)
                {
                    movieCoised = true;
                    MovieChoosedFrom = choosedFrom.ExactMatches;
                    tmp = MoviesIMDBResultset.ExactMatches.First();
                }
                else
                {
                    if (MoviesIMDBResultset.PopularTitles != null && MoviesIMDBResultset.PopularTitles.Count > 0)
                    {
                        if (YearByName > 0)
                        {
                            tmpList = MoviesIMDBResultset.PopularTitles.FindAll(p => p.Year == YearByName && p.Title.ToLower() == NewName.ToLower());

                            if (tmpList.Count == 1)
                            {
                                movieCoised = true;
                                MovieChoosedFrom = choosedFrom.PopularTitles;
                                tmp = tmpList.First();
                            }
                        }
                        else
                        {
                            tmpList = MoviesIMDBResultset.PopularTitles.FindAll(p => p.Title.ToLower() == NewName.ToLower());
                            if (tmpList.Count == 1)
                            {
                                movieCoised = true;
                                MovieChoosedFrom = choosedFrom.PopularTitles;
                                tmp = tmpList.First();
                            }
                        }

                    }
                    else if (MoviesIMDBResultset.ExactMatches != null && MoviesIMDBResultset.ExactMatches.Count > 0)
                    {
                        if (YearByName > 0)
                        {
                            tmpList = MoviesIMDBResultset.ExactMatches.FindAll(p => p.Year == YearByName && p.Title.ToLower() == NewName.ToLower());

                            if (tmpList.Count == 1)
                            {
                                movieCoised = true;
                                MovieChoosedFrom = choosedFrom.ExactMatches;
                                tmp = tmpList.First();
                            }
                        }
                        else
                        {
                            tmpList = MoviesIMDBResultset.ExactMatches.FindAll(p => p.Title.ToLower() == NewName.ToLower());

                            if (tmpList.Count == 1)
                            {
                                movieCoised = true;
                                MovieChoosedFrom = choosedFrom.ExactMatches;
                                tmp = tmpList.First();
                            }
                        }
                    }
                }

                if (movieCoised && tmp != null)
                {
                    Imdb.GetMovieAsync(tmp.Id, true); //0499549 avatar  //0133093 matrix
                    MovieStatus = moviesStatuses.ImdbSynched;
                }
                else
                    MovieStatus = moviesStatuses.ImdbNotSynched;

            }

            if(ImdbSynchronisationDone != null) ImdbSynchronisationDone(this.NewName);
        }

        private void Imdb_MovieParsed(Imdb.Movie M)
        {
            this.MovieIMDBInfo = M;
            this.MovieSynhName = M.Title;
            this.NewName = M.Title;
            RefreshMovePoster();
            UpdateMovieInRecordSet();
        }

        private void UpdateMovieInRecordSet()
        {
            switch (MovieChoosedFrom)
            {
                case choosedFrom.PopularTitles:
                    var tempPop = MoviesIMDBResultset.PopularTitles.FirstOrDefault(p => p.Id == MovieIMDBInfo.Id);
                    int iPop = MoviesIMDBResultset.PopularTitles.IndexOf(tempPop);
                     MovieIMDBInfo.AlreadyDownloaded = true;
                     MoviesIMDBResultset.PopularTitles.Remove(tempPop);
                     MoviesIMDBResultset.PopularTitles.Insert(iPop, MovieIMDBInfo);
                    break;
                case choosedFrom.ExactMatches:
                     var tempExa = MoviesIMDBResultset.ExactMatches.FirstOrDefault(p => p.Id == MovieIMDBInfo.Id);
                     int iExa = MoviesIMDBResultset.ExactMatches.IndexOf(tempExa);
                     MovieIMDBInfo.AlreadyDownloaded = true;
                     MoviesIMDBResultset.ExactMatches.Remove(tempExa);
                     MoviesIMDBResultset.ExactMatches.Insert(iExa, MovieIMDBInfo);
                     break;
                case choosedFrom.PartialMatches:
                     var tempPar = MoviesIMDBResultset.PartialMatches.FirstOrDefault(p => p.Id == MovieIMDBInfo.Id);
                     int iPar = MoviesIMDBResultset.PartialMatches.IndexOf(tempPar);
                     MovieIMDBInfo.AlreadyDownloaded = true;
                     MoviesIMDBResultset.PartialMatches.Remove(tempPar);
                     MoviesIMDBResultset.PartialMatches.Insert(iPar, MovieIMDBInfo);
                     break;
            }
        }

        public void RefreshMovePoster()
        {
            if (MovieIMDBInfo != null)
            {
                MovieIMDBInfo.Poster = null;
                download_Poster(MovieIMDBInfo.PosterUrl);
            }
        }

        private void download_Poster(string imgUrl)
        {
            MovieIMDBInfo.Poster = Properties.Resources.ajax_loader;
            using (var Wc = new System.Net.WebClient())
            {
                Wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(Wc_DownloadDataCompleted);
                Wc.DownloadDataAsync(new Uri(imgUrl));
            }
        }

        private void Wc_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
        {
            ((System.Net.WebClient)sender).DownloadDataCompleted -= Wc_DownloadDataCompleted;
            MovieIMDBInfo.Poster = System.Drawing.Image.FromStream(new System.IO.MemoryStream(e.Result));
        }

        public void SaveMovieConf()
        {
            XmlSerializer xser = new XmlSerializer(typeof(VMovie));
            MemoryStream m = new MemoryStream();
            xser.Serialize(m, this);
            File.WriteAllBytes(Path.Combine(FullPath, "vmconf"), m.GetBuffer());
            m.Close();
            if(File.Exists((Path.Combine(FullPath, "vmconf"))))
                File.SetAttributes(Path.Combine(FullPath, "vmconf"), FileAttributes.Hidden);
             if(File.Exists((Path.Combine(FullPath, "Folder.jpg"))))
                 File.SetAttributes(Path.Combine(FullPath, "Folder.jpg"), FileAttributes.Hidden);
        }
    }

    public class VMovieCollection : List<VMovie>
    {
        public VMovieCollection() { }

        public VMovieCollection(IEnumerable<VMovie> Items) : base(Items) { }
    }


}
